//
//  RemoteNotificationHandleService.swift
//  mggz
//
//  Created by ShareAnimation on 2017/11/3.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import ObjectMapper
import MMDrawerController
class RemoteNotificationHandleService: NSObject {
    enum NotifitionType {
        case BGT//包工头
        case MG//民工
        case JGBM//监管部门
    }
    
    //处理远程推送
    class func handleRemoteNotification(_ userInfo:[AnyHashable: Any]) {
        var typeString:String?
        var apsDic:[String:AnyObject]?
        let service = RemoteNotificationHandleService()
        //如果推送有扩展字段『type』，说明需要弹框处理
        if let typeStr = userInfo["type"] as? String {
            typeString = typeStr
        }else{
            typeString = ""
        }
        if let dict = userInfo["aps"] as? [String:AnyObject]{
            apsDic = dict
        }else{
            apsDic = ["sound":"default"] as [String : AnyObject]
        }
        service.presentAlert(typeString!, apsDic: apsDic!)
    }
    
    //点击推送时，判断是否要跳转到messageList页
    class func handleRemoteNotificationWhenClick(_ userInfo:[AnyHashable: Any]) {
        switch self.utilContractor(userInfo){
        case .BGT:
            if (ContractorName != nil || ContractorPass != nil) && LoginType == 2{
                
                let vc = MessageController(nibName: "MessageController", bundle: nil)
                vc.isPresent = true
                let v = UIApplication.shared.delegate?.window!?.rootViewController
                if v is MMDrawerController{
                    print("MMDrawerController")
                    v?.present(vc, animated: true, completion: nil)
                }
                
            }
            break
        case .MG:
            LoginAuthenticationService.verifyLoginStatus { (response) in
                if response.success {
                    let vc = MessageListController()
                    vc.hidesBottomBarWhenPushed = true
                    Tool.topViewController().navigationController?.pushViewController(vc, animated: true)
                }
            }
            break;
        case .JGBM:
            break
        default:
            break
        }
    }
    //包工头处理
    class func utilContractor(_ userInfo:[AnyHashable: Any]) -> NotifitionType
    {
        
        var typeString = userInfo["type"] as? String
        if (typeString?.contains("劳务公司")) ?? false{
            return .BGT
        }else if (typeString?.contains("民工工资")) ?? false{
            return .MG
        }else{
            return .JGBM
        }
        
    }
    /// 弹框处理
    ///
    /// - Parameters:
    ///   - type: 弹窗类型
    ///   - date: 推送到达手机的时间。
    func presentAlert(_ type: String,apsDic:[String:AnyObject]) {
        let service = RemoteNotificationHandleService()
        var jsonData:String?
        jsonData = type
        
        let confirmStr = jsonData?.replacingOccurrences(of: String("\\"), with: "")
        let dict:[String : AnyObject]? = getDictionaryFromJsonString(jsonString: confirmStr!)
        guard dict != nil else{
            return
        }
        print(type)
        print(dict)
        
        if let type = dict!["Type"] as? String {
            if let notificationType = AlertShowType(rawValue: type) {
                switch notificationType {
                case .autoSignedOut:
                    service.showSignedOutAlert(dict!)
                case .autoSignedIn:
                    service.showSignedInAlert(dict!)
                case .applyCallIn:
                    service.showApplyCallInAlert(dict!)
                case .addWorker:
                    service.showAddWorkerAlert(dict!)
                case .salaryPayed:
                    service.showSalaryPayedAlert(dict!)
                case .signInWarn:
                    service.showUrgeSignedInAlert(dict!, sort: "1")
                case .signOutWarn:
                    service.showUrgeSignedInAlert(dict!, sort: "2")
                case .overtimeWarn:
                    service.showUrgeSignedInAlert(dict!, sort: "3")
                case .leaveIceWarn:
                    service.ShowleaveOutAlert(dict!)
                case .downLine:
                    service.downlineAction(dict!)
                case .payroll:
                    service.showPayrollAlertView(dict!, apsDic: apsDic)
                case .paymentSure:
                    service.showPaymentSureAlertView(dict!, apsDic: apsDic)
                case .wagePayment:
                    service.showWagePaymentAlertView(dict!, apsDic: apsDic)
                default:
                    break
                }
            }
        }
    }
    
    //MARK:各种弹框
    /// 签出弹框
    ///
    /// - Parameters:
    ///   - dict: <#dict description#>
    
    //工资预告
    func showPayrollAlertView(_ dict: [String: AnyObject],apsDic:[String: AnyObject]){
        var demandBaseMigrantWorkerID: [String: Any]?
        var alertDic:[String: Any]?
        if let params = dict["Params"] as? [String: Any] {
            demandBaseMigrantWorkerID = params
        }
        if let alertDiction = apsDic["alert"] as? [String: Any]{
            alertDic = alertDiction
        }
        print(alertDic)
        let alert = ETAppealAlertViewController.init(demandBaseMigrantWorkerID!, dict: alertDic!) {
            
        }
        Tool.topViewController().present(alert, animated: true, completion: nil)
    }
    
    func showWagePaymentAlertView(_ dict: [String: AnyObject],apsDic:[String: AnyObject]){
        
        
        
        
        
        
    }
    func showPaymentSureAlertView(_ dict: [String: AnyObject],apsDic:[String: AnyObject]){
        var demandBaseMigrantWorkerID: [String: Any]?
        var alertDic:[String: Any]?
        if let params = dict["Params"] as? [String: Any] {
            demandBaseMigrantWorkerID = params
        }
        if let alertDiction = apsDic["alert"] as? [String: Any]{
            alertDic = alertDiction
        }
        
        let alert = ETComplaintViewController.init(demandBaseMigrantWorkerID!, dict: alertDic!) {
            
        }
        Tool.topViewController().present(alert, animated: true, completion: nil)
    }
    
    
    // 催签弹框
    
    func showUrgeSignedInAlert(_ dict: [String: AnyObject],sort:String) {
        if (Tool.topViewController().presentingViewController == nil){
            let rangeStr = LoginAuthenticationService.getupIsRangeData()
            if rangeStr == "1"{
                var demandBaseMigrantWorkerID: String?
                if let params = dict["Params"] as? [String: Any] {
                    demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
                }
                
                let alert = ETSpecialAlertViewController.init(sort, demandBaseMigrantWorkerID: demandBaseMigrantWorkerID!) {
                    
                }
                Tool.topViewController().present(alert, animated: true, completion: nil)
            }else{
                var demandBaseMigrantWorkerID: String?
                if let params = dict["Params"] as? [String: Any] {
                    demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
                }
                
                let alert = ETOutRangeAlertController.init(sort, demandBaseMigrantWorkerID: demandBaseMigrantWorkerID!) {
                    
                    
                }
                Tool.topViewController().present(alert, animated: true, completion: nil)
            }
        }
    }
    
    //离场的弹框
    func ShowleaveOutAlert(_ dict: [String: AnyObject]){
        if (Tool.topViewController().presentingViewController == nil){
            var demandBaseMigrantWorkerID: String?
            if let params = dict["Params"] as? [String: Any] {
                demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
            }
            let alert = ETOutRangeAlertController.init("4", demandBaseMigrantWorkerID: demandBaseMigrantWorkerID!) {
                
            }
            Tool.topViewController().present(alert, animated: true, completion: nil)
        }
    }
    func showSignedOutAlert(_ dict: [String: AnyObject]) {
        var demandBaseMigrantWorkerID: String?
        if let params = dict["Params"] as? [String: Any] {
            demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
        }
        let alert = ETSignedOutAlertController.init(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)
        Tool.topViewController().present(alert, animated: true, completion: nil)
    }
    
    //
    /// 签入弹框
    ///
    /// - Parameters:
    ///   - dict: <#dict description#>
    func showSignedInAlert(_ dict:[String: AnyObject]) {
        var demandBaseMigrantWorkerID: String?
        if let params = dict["Params"] as? [String: Any] {
            demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
        }
        let alert = ETSignedInAlertController.init(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)
        Tool.topViewController().present(alert, animated: true, completion: nil)
    }
    
    func downlineAction(_ dict: [String: AnyObject]){
        WWUser.sharedInstance.loginOut()
        let vc = LoginViewController()
        UIApplication.shared.delegate?.window!?.rootViewController = vc
        (UIApplication.shared.delegate as! AppDelegate).setTags(nil)
        TrackUploadService.sharedInstance.stop()
        TrackUploadService.sharedInstance.stopBackGroundLocation()
        var demandBaseMigrantWorkerID: String?
        if let params = dict["Params"] as? [String: Any] {
            demandBaseMigrantWorkerID = params["Message"] as? String
        }
        let alert = ETDownLineAlertController.init(demandBaseMigrantWorkerID!) {
            
        }
        Tool.topViewController().present(alert, animated: true, completion: nil)
    }
    //调入申请弹框
    func showApplyCallInAlert(_ dict:[String: AnyObject]) {
        if let params = dict["Params"] as? [String: Any] {
            let alert = ETProjectApplicationAlertController.init(dict: params,style: .apply)
            Tool.topViewController().present(alert, animated: true, completion: nil)
        }
        
    }
    
    //拉入民工弹框
    func showAddWorkerAlert(_ dict:[String: AnyObject]) {
        if let params = dict["Params"] as? [String: Any] {
            let alert = ETProjectApplicationAlertController.init(dict: params,style: .add)
            Tool.topViewController().present(alert, animated: true, completion: nil)
        }
        
    }
    
    //工资发放弹框
    func showSalaryPayedAlert(_ dict:[String: Any]) {
        if let params = dict["Params"] as? [String: Any] {
            let alert = ETSalaryCalculationAlertController.init(dict: params)
            Tool.topViewController().present(alert, animated: true, completion: nil)
        }
    }
    
    /// 根据远程推送的类型进行不同的弹框。
    ///
    /// - Parameters:
    ///   - extras:
    ///   - isPressed: true表示当前是点击推送，false是前台收到推送
    func alertPresentOnType(_ extras: [AnyHashable: Any] , isPressed: Bool) {
        if let typeString = extras["type"] as? String {
            let dict = getDictionaryFromJsonString(jsonString: typeString)
            
            guard dict != nil else{
                return
            }
            if let type = dict!["Type"] as? String {
                
                if let notificationType = AlertShowType(rawValue: type) {
                    switch notificationType {
                    case .autoSignedOut:
                        if !isPressed {
                            var demandBaseMigrantWorkerID: String?
                            if let params = dict!["Params"] as? [String: Any] {
                                demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
                            }
                            
                            let alert = ETSignedOutAlertController.init(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)
                            Tool.topViewController().present(alert, animated: true, completion: nil)
                        }
                        
                    case .autoSignedIn:
                        
                        if !isPressed {
                            var demandBaseMigrantWorkerID: String?
                            if let params = dict!["Params"] as? [String: Any] {
                                demandBaseMigrantWorkerID = params["DemandBaseMigrantWorkerID"] as? String
                            }
                            let alert = ETSignedInAlertController.init(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID)
                            Tool.topViewController().present(alert, animated: true, completion: nil)
                        }
                        
                    case .applyCallIn:
                        if let params = dict!["Params"] as? [String: Any] {
                            let alert = ETProjectApplicationAlertController.init(dict: params,style: .apply)
                            Tool.topViewController().present(alert, animated: true, completion: nil)
                        }
                    case .addWorker:
                        if let params = dict!["Params"] as? [String: Any] {
                            let alert = ETProjectApplicationAlertController.init(dict: params,style: .add)
                            Tool.topViewController().present(alert, animated: true, completion: nil)
                        }
                    case .salaryPayed:
                        if let params = dict!["Params"] as? [String: Any] {
                            let alert = ETSalaryCalculationAlertController.init(dict: params)
                            Tool.topViewController().present(alert, animated: true, completion: nil)
                        }
                    default:
                        //如果是点击推送，则没有满足以上情况下跳转到MessageListController。
                        //如果是前台收到推送，没有满足以上情况下不做处理
                        if isPressed {
                            LoginAuthenticationService.verifyLoginStatus { (response) in
                                if response.success {
                                    let vc = MessageListController()
                                    vc.hidesBottomBarWhenPushed = true
                                    Tool.topViewController().navigationController?.pushViewController(vc, animated: true)
                                }
                            }
                        }
                        break
                    }
                }
                else {
                    if isPressed {
                        LoginAuthenticationService.verifyLoginStatus { (response) in
                            if response.success {
                                let vc = MessageListController()
                                vc.hidesBottomBarWhenPushed = true
                                Tool.topViewController().navigationController?.pushViewController(vc, animated: true)
                            }
                        }
                    }
                }
            }
        }
        else {
            if isPressed {
                LoginAuthenticationService.verifyLoginStatus { (response) in
                    if response.success {
                        let vc = MessageListController()
                        vc.hidesBottomBarWhenPushed = true
                        Tool.topViewController().navigationController?.pushViewController(vc, animated: true)
                    }
                }
            }
        }
    }
}
